package com.hoshiicloud.user.controller.usercenter;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.user.controller.BaseController;
import com.hoshiicloud.user.entity.usercenter.MemberIntegration;
import com.hoshiicloud.user.param.usercenter.MemberIntegrationPageParam;
import com.hoshiicloud.user.param.usercenter.MemberIntegrationUpdateParam;
import com.hoshiicloud.user.service.usercenter.IMemberIntegrationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户积分Controller类
 *
 * @author : yangcheng
 * @date : 2019/5/13 10:53
 * @mail : maiboyc@163.com
 **/
@RestController
@RequestMapping("/memberIntegration")
@Api(value = "用户积分管理", tags = {"用户积分操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class MemberIntegrationController extends BaseController {

    // 用户积分Service
    @Autowired
    private IMemberIntegrationService memberIntegrationService;

    /**
     * 根据ID查询用户积分
     * @param id ID
     * @return Response
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询", notes = "根据ID查询用户积分信息", consumes = MediaType.ALL_VALUE)
    public Response<MemberIntegration> getById(@PathVariable("id") Long id) {
        Response<MemberIntegration> rs;
        try {
            rs = Response.data(memberIntegrationService.getById(id));
        } catch (Exception e) {
            logger.error("根据ID查询用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID组查询用户积分
     * @param ids ID组
     * @return Response
     */
    @GetMapping("/getByIds")
    @ApiOperation(value = "根据ID组查询", notes = "根据ID组查询用户积分信息", consumes = MediaType.ALL_VALUE)
    public Response<List<MemberIntegration>> getByIds(@RequestParam("ids") List<Long> ids) {
        Response<List<MemberIntegration>> rs;
        try {
            rs = Response.data(memberIntegrationService.getByIds(ids));
        } catch (Exception e) {
            logger.error("根据ID组查询用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据积分编号查询用户积分
     * @param integrationno  积分编号
     * @return Response
     */
    @GetMapping("/find/{integrationno}")
    @ApiOperation(value = "根据积分编号查询", notes = "根据积分编号查询用户积分信息", consumes = MediaType.ALL_VALUE)
    public Response<IPage<MemberIntegration>> findByName(@PathVariable("integrationno") String integrationno) {
        Response<IPage<MemberIntegration>> rs;
        try {
            MemberIntegration entity = new MemberIntegration();
            entity.setIntegrationno(integrationno);
            rs = Response.data(memberIntegrationService.List(entity));
        } catch (Exception e) {
            logger.error("根据积分编号查询用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询用户积分（get请求，以具体值接收参数）
     * @param pageIndex         当前页码
     * @param pageSize          每页显示的记录数
     * @param userId            用户主键ID
     * @param integrationno     积分编号
     * @param source            来源
     * @param status            状态
     * @return Response
     */
    @GetMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询用户积分信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "当前页码", required = true, dataType = "Long", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "Long", example = "10", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户主键ID", dataType = "Long", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "integrationno", value = "积分编号", dataType = "String", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Integer", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "source", value = "涞源", dataType = "Integer", example = "1", paramType = "query")
    })
    public Response<IPage<MemberIntegration>> list(Long pageIndex, Long pageSize, Long userId, String integrationno, Integer source, Integer status ) {
        Response<IPage<MemberIntegration>> rs;
        try {
            MemberIntegration entity = new MemberIntegration();
            entity.setPageIndex(pageIndex);
            entity.setPageSize(pageSize);
            entity.setUserId(userId);
            entity.setIntegrationno(integrationno);
            entity.setSource(source);
            entity.setStatus(status);
            rs = Response.data(memberIntegrationService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询用户积分（post请求，以对象接收参数）
     * @param param 查询参数实体
     * @return Response
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询用户积分信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<IPage<MemberIntegration>> list(@RequestBody MemberIntegrationPageParam param) {
        Response<IPage<MemberIntegration>> rs;
        try {
            MemberIntegration entity = new MemberIntegration();
            BeanUtils.copyProperties(param, entity);
            rs = Response.data(memberIntegrationService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 新增用户积分
     * @param entity 保存参数实体
     * @return Response
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增用户积分", notes = "新增用户积分信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> save(@RequestBody @Valid MemberIntegration entity, BindingResult result) {
        Response<Long> rs;
        try {
            if (CollectionUtils.isNotEmpty(handleValidMsg(result))){// 验证不通过
                rs = Response.failed(objectMapper.writeValueAsString(handleValidMsg(result)));
            } else {// 验证通过
                rs = Response.data(memberIntegrationService.insert(entity));
            }
        } catch (JsonProcessingException e) {
            logger.error("处理JSON验证信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        } catch (ServiceException e) {
            logger.error("新增用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        }catch (Exception e) {
            logger.error("新增用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 修改用户积分
     * @param param 修改参数实体
     * @return Response
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改用户积分", notes = "修改用户积分信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> updateById(@RequestBody @Valid MemberIntegrationUpdateParam param, BindingResult result) {
        Response<Long> rs;
        try {
            if (CollectionUtils.isNotEmpty(handleValidMsg(result))){// 验证不通过
                rs = Response.failed(objectMapper.writeValueAsString(handleValidMsg(result)));
            } else {// 验证通过
                MemberIntegration entity = new MemberIntegration();
                BeanUtils.copyProperties(param, entity);
                rs = Response.data(memberIntegrationService.update(entity));
            }
        } catch (JsonProcessingException e) {
            logger.error("处理JSON验证信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        } catch (ServiceException e) {
            logger.error("更新用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("更新用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID删除用户积分
     * @param id 用户ID
     * @return Response
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除用户积分信息", consumes = MediaType.ALL_VALUE)
    public Response<Boolean> deleteById(@PathVariable("id") Long id) {
        Response<Boolean> rs;
        try {
            rs = Response.data(memberIntegrationService.delete(id));
        } catch (ServiceException e) {
            logger.error("删除用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("删除用户积分信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }
    
}  